package org.finmanager.core;

import java.util.Observable;
import java.util.Observer;

/**
 * Created by Kelvin on 26/4/2014.
 */

//Defining models which will be easier used
public class ItemModel extends Observable implements Observer {
	private FinManager finManager;

	private ItemTableModel itemTableModel;

	public ItemModel(FinManager finManager) {
		this.finManager = finManager;
		itemTableModel = new ItemTableModel(finManager.getItemList());
	}

	public ItemTableModel getItemTableModel() {
		return itemTableModel;
	}

	public void addItem(Item item) {
		finManager.getItemList().addItem(item);
		int index = finManager.getItemList().getItemCount() - 1;
		itemTableModel.fireTableRowsInserted(index, index);

		setChanged();
		notifyObservers();
	}

	public void editItem(int index, Item item) {
		finManager.getItemList().setItem(index, item);
		itemTableModel.fireTableDataChanged();

		setChanged();
		notifyObservers();
	}

	public void deleteItem(int index) {
		finManager.getItemList().deleteItem(index);
		itemTableModel.fireTableDataChanged();

		setChanged();
		notifyObservers();
	}

	public void deleteRowWithCategory(Category category) {
		finManager.getItemList().deleteItemsWithCategory(category);
		itemTableModel.fireTableDataChanged();

		setChanged();
		notifyObservers();
	}



	@Override
	public void update(Observable o, Object arg) {
		if (arg != null) {
			Category category = (Category) arg;
			deleteRowWithCategory(category);
		}
	}
}
